﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 Simple.Utils
 * 接口名称 SimpleCheck
 * 开发人员：zdm
 * 创建时间：2023/11/3 10:37:45
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace Simple.Tools
{
	public  static class ToolSimpleCheck
	{
		public static bool IsNullOrEmpty(this string value)
		{
			return string.IsNullOrEmpty(value);
		}

		public static bool IsNullOrEmpty<T>(this IEnumerable<T> array)
		{
			return array == null || array.Count() == 0;
		}

		public static void IsNullThrowException(this object o)
		{
			if (IsNull(o))
			{
				throw new ArgumentNullException("");
			}
		}

		public static void IsNullThrowException(this object o,string msg)
		{
			if (IsNull(o))
			{
				throw new ArgumentNullException(msg);
			}
		}

		public static Boolean IsEmpty(this Guid o)
		{
			return o == Guid.Empty;
		}

		public static Boolean IsNull(this object o)
		{
			return o==null;
		}

		public static string IsNullGetEmpty(this string value)
		{
			if (IsNullOrEmpty(value))
			{
				return string.Empty;
			}
			else
			{
				return value;
			}
		}

		/// <summary>
		/// 如果文件不存在就创建文件
		/// </summary>
		/// <param name="FilePath"></param>
		public static void CreateFile(string FilePath)
		{
			if (!File.Exists(FilePath))
			{
				if (!FilePath.Contains(AppDomain.CurrentDomain.BaseDirectory))
				{
					FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FilePath);
				}
				if (!Directory.Exists(Path.GetDirectoryName(FilePath)))
				{
					Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
				}
				File.Create(FilePath);
				Task.Delay(300).Wait();
			}
		}


		public static IPAddress GetLocalHostFirstOrDefault()
		{
			try
			{
				//NetworkInterface：提供网络接口的配置和统计信息。
				NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
				foreach (NetworkInterface adapter in adapters)
				{
					IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
					UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;
					//这里是根据网络适配器名称找到对应的网络，adapter.Name即网络适配器的名称

					foreach (UnicastIPAddressInformation addr in allAddress)
					{
                        if (addr.Address.AddressFamily == AddressFamily.InterNetwork && addr.DuplicateAddressDetectionState== DuplicateAddressDetectionState.Preferred)
						{
                            return addr.Address;
						}
					}
				}
			}
			catch (Exception ex)
			{
			}
			finally
			{
			}
			 IPAddress.TryParse("127.0.0.1", out IPAddress ipaddress);
			return ipaddress;

		}


		public static IList<string> GetLocalHosts(DuplicateAddressDetectionState state= DuplicateAddressDetectionState.Preferred)
		{
			IList<string> strIp = new List<string>();
			try
			{
				//NetworkInterface：提供网络接口的配置和统计信息。
				NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
				foreach (NetworkInterface adapter in adapters)
				{
					IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
					UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;
					//这里是根据网络适配器名称找到对应的网络，adapter.Name即网络适配器的名称

					foreach (UnicastIPAddressInformation addr in allAddress)
					{
						if (addr.Address.AddressFamily == AddressFamily.InterNetwork && state == addr.DuplicateAddressDetectionState)
						{
                            strIp.Add(addr.Address.ToString());
						}
					}
				}
			}
			catch (Exception ex)
			{
			}
			finally
			{
			}
			return strIp;
		}

		
		public static bool PlatformIsLinux()
		{
			return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
		}

		public static bool PlatformIsWindows()
		{
			return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
		}

		public static bool PlatformIsFreeBSD()
		{
			return RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD);
		}
		private static bool? _isDebugMode;
		public static bool IsDebug()
		{

			if (_isDebugMode == null)
			{
				var assembly = Assembly.GetEntryAssembly();
				if (assembly == null)
				{
					// 由于调用 GetFrames 的 StackTrace 实例没有跳过任何帧，所以 GetFrames() 一定不为 null。
					assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
				}

				var debuggableAttribute = assembly.GetCustomAttribute<DebuggableAttribute>();
				_isDebugMode = debuggableAttribute.DebuggingFlags
					.HasFlag(DebuggableAttribute.DebuggingModes.EnableEditAndContinue);
			}
			return _isDebugMode.Value;
		}


		public static string GetLiunxSN()
		{
			return Bash("cat /etc/machine-id");
		}

		public static string Bash(this string cmd)
		{
			string result = String.Empty;

			try
			{
				var escapedArgs = cmd.Replace("\"", "\\\"");

				using (Process process = new Process())
				{
					process.StartInfo = new ProcessStartInfo
					{
						FileName = "/bin/bash",
						Arguments = $"-c \"{escapedArgs}\"",
						RedirectStandardOutput = true,
						UseShellExecute = false,
						CreateNoWindow = true,
					};

					process.Start();
					result = process.StandardOutput.ReadToEnd();
					process.WaitForExit(1500);
					process.Kill();
				};
			}
			catch (Exception ex)
			{
				//Logger.ErrorFormat(ex.Message, ex);
			}
			return result;
		}
	}
}
